package com.axialproject.health.exchange.google;

import com.axialproject.health.exchange.EMF;
import com.axialproject.health.exchange.PatientManager;
import com.axialproject.health.exchange.entity.Patient;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.EntityManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UnlinkServlet extends HttpServlet {

    private static final Logger log = Logger.getLogger(UnlinkServlet.class.getName());

    public void doGet (HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {

        String appUrl = this.getServletContext().getInitParameter("AppUrl");

        // Input parameters: appName, patientId
        String appName = req.getParameter ("appName");
        String username = req.getParameter ("username");
        String nextUrl = req.getParameter ("nextUrl");

        EntityManager em = EMF.get().createEntityManager();
        try {
            Patient patient = PatientManager.getPatientByUsernameAppName(em, username, appName);
            if (patient == null) {
                throw new Exception ("We cannot find the account to unlink from google. Exit");
            } else {
                List <Patient> patients = PatientManager.getLinkedPatients(em, patient.getId());
                if (patients == null) {
                    patients = new ArrayList <Patient> ();
                }
                for (Patient p : patients) {
                    if ("google".equals(p.getAppName()) && p.getToken() != null) {
                        PatientManager.removePatientLink(em, patient.getId(), p.getId());
                        PatientManager.removePatient(em, p);
                        break;
                    }
                }
            }

        } catch (Exception e) {
            log.log(Level.SEVERE, e.getMessage(), e);
            resp.sendRedirect (nextUrl + "?success=0");
            return;
        } finally {
            em.close ();
        }

        resp.sendRedirect (nextUrl + "?success=1");
    }

    public void doPost (HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        doGet (req, resp);
    }
}